package cn.bigcontainer.alt.meta.extension.impl;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import cn.bigcontainer.alt.meta.dao.MDao;
import cn.bigcontainer.alt.meta.dto.MViewDto;
import cn.bigcontainer.alt.meta.extension.MFormKeyValueAdaptor;
import cn.bigcontainer.alt.meta.po.MRelation;
import cn.bigcontainer.alt.meta.util.MUtil;

/**
 * @author jiaod
 * @date 2021年5月10日
 */
@Component
@Primary
public class MCurrentUserKeyValueAdaptor implements MFormKeyValueAdaptor {

	@Resource
	private MDao dao;
	
	@Override
	public String getKeyValues(MViewDto form) {
		Map<String, Object> req = form.getApp().getObject().getRequest();
		Integer currentUserId = MUtil.getCurrentUserId(req);
		if (currentUserId == null) {
			return null;
		}
		for (MRelation r : form.getApp().getObject().getRelations()) {
			if (r.isM21() && r.getRelatedObjectId().equals("sys_user")) {
				String sql = String.format("select %s from %s where %s = '%d'",
						form.getApp().getObject().getKeyProperties().get(0).getName(), form.getObjectId(),
						r.getProperties().get(0).getName(), currentUserId);
				return dao.queryString(sql);
			}
		}
		return currentUserId.toString();
	}

}
